<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\Company;
use App\Models\Admin\Order;
use Carbon\Carbon;
use Illuminate\Http\Request;
use DB;

class CompanyAnalysisController extends AdminController
{
    use AdminTrait;

    public function __construct()
    {

    }

    public function index(BaseRequest $request)
    {
        $start_time = $request->query('start_time') ?? date("Y-m-d");
        $end_time = $request->query('end_time') ?? date("Y-m-d");

        $order_money = DB::table('statistics_customer_day')->whereBetween('timestamps',[strtotime($start_time),strtotime($end_time)])->sum('order_money');
        $send_money = DB::table('statistics_customer_day')->whereBetween('timestamps',[strtotime($start_time),strtotime($end_time)])->sum('amount');
        $order_num = DB::table('statistics_customer_day')->whereBetween('timestamps',[strtotime($start_time),strtotime($end_time)])->sum('order_volume');
        $order_price = ($order_num > 0) ? round(($order_money/$order_num),2) : 0;
        $cost_money = DB::table('statistics_customer_day')->whereBetween('timestamps',[strtotime($start_time),strtotime($end_time)])->sum('cost');
        $profit_money = round(($send_money-$cost_money),2);
        $profit_rate = ($send_money > 0) ? round(($profit_money/$send_money)*100,2) : 0;


        $count_company = Company::count();
        $count_software = Company::where('model',3)->count();//软件
        $count_delivery = Company::where('model',2)->count();//城配
        $count_dispatch = Company::where('model',1)->count();//批发
        //正常一周内有订单则是正常使用，在服务期内
        $company_ids = Order::select('company_id')->where('created_at','>',Carbon::now()->subDays(7)->timestamp)->groupBy('company_id')->get()->pluck('company_id');
        $count_normal = Company::where('status',1)->where('end_time','>',time())->whereIn('id',$company_ids)->count();//正常使用
        //正常一周内无订单则不正常使用，在服务期内
        $count_forbid = Company::where('status',1)->where('end_time','>',time())->whereNotIn('id',$company_ids)->count();//未使用
        //正常不在服务区或已禁用
        $count_stop = Company::orWhere('status',0)->orWhere(function ($query) {
            $query->where('status',1)->where('end_time','<',time());
        })->count();//停止使用
        //$count_normal = $count_normal - $count_stop;
        $normal_rate = ($count_company > 0) ? round(($count_normal/$count_company)*100,2).'%'  : "0%";//正常占比

        //$graph = $this->getGraphData('send_money',$start_time,$end_time);
        //$histogram = $this->getHistogramData('send_money',$start_time,$end_time);
        $company_rate = [
            [
                'name' => '城配',
                'rate' => round(($count_software/$count_company)*100,2)
            ],
            [
                'name' => '软件',
                'rate' => round(($count_delivery/$count_company)*100,2)
            ],
            [
                'name' => '批发',
                'rate' => round(($count_dispatch/$count_company)*100,2)
            ]
        ];

        return $this->success([
            'count_company' => $count_company,
            'count_software' => $count_software,
            'count_delivery' => $count_delivery,
            'count_dispatch' => $count_dispatch,
            'count_normal' => $count_normal,
            'count_forbid' => $count_forbid,
            'count_stop' => $count_stop,
            'normal_rate' => $normal_rate,
            //'histogram' => $histogram,
            'company_rate' => $company_rate,
            //'graph' => $graph,
            'order_money' => $order_money,//下单金额
            'send_money' => $send_money,//配送金额
            'order_num' => $order_num,//订单数量
            'order_price' => $order_price,//平均订单价
            'profit_money' => $profit_money,//利润金额
            'profit_rate' => $profit_rate//利润率
        ]);
    }

    public function getHistogram(BaseRequest $request)
    {
        $start_time = $request->query('start_time') ?? date("Y-m-d");
        $end_time = $request->query('end_time') ?? date("Y-m-d");
        $field = $request->query('field') ?? 'send_money';
        $histogram = $this->getHistogramData($field,$start_time,$end_time);
        return $this->success(['histogram' => $histogram]);
    }

    protected function getHistogramData($field='send_money',$start_time,$end_time,$limit=10)
    {
        $this->checkField($field);
        $select = DB::table('statistics_customer_day');
        switch ($field) {
            case 'send_money' :
                $select = $select->selectRaw("SUM(amount) as money,(SELECT company_name FROM ".config('database.connections.mysql.prefix')."company WHERE company_id=id) as company_name");
                break;
            case 'order_num' :
                $select = $select->selectRaw("SUM(order_volume) as money,(SELECT company_name FROM ".config('database.connections.mysql.prefix')."company WHERE company_id=id) as company_name");
                break;
            case 'cost_money' :
                $select = $select->selectRaw("SUM(cost) as money,(SELECT company_name FROM ".config('database.connections.mysql.prefix')."company WHERE company_id=id) as company_name");
                break;
            case 'order_money' :
                $select = $select->selectRaw("SUM(order_money) as money,(SELECT company_name FROM ".config('database.connections.mysql.prefix')."company WHERE company_id=id) as company_name");
                break;
            case 'profit_money' :
                $select = $select->selectRaw("SUM(ROUND(amount-cost,2)) as money,(SELECT company_name FROM ".config('database.connections.mysql.prefix')."company WHERE company_id=id) as company_name");
                break;
            case 'profit_rate' :
                $select = $select->selectRaw("IF(SUM(amount) > 0,ROUND((SUM(ROUND(amount-cost,2))/SUM(amount))*100,2),0) as money,(SELECT company_name FROM ".config('database.connections.mysql.prefix')."company WHERE company_id=id) as company_name");
                break;
        }
        $select = $select->whereBetween('timestamps',[strtotime($start_time),strtotime($end_time)])->groupBy('company_id');
        if ($limit) {
            $select = $select->limit($limit);
        }
        $list = $select->orderBy('money','desc')->get()->toArray();
        return $list;
    }

    public function getGraph(BaseRequest $request)
    {
        $start_time = $request->query('start_time') ?? date("Y-m-d");
        $end_time = $request->query('end_time') ?? date("Y-m-d");
        $field = $request->query('field') ?? 'send_money';
        $graph = $this->getGraphData($field,$start_time,$end_time);
        return $this->success(['graph' => $graph]);
    }

    protected function getGraphData($field='send_money',$start_time,$end_time)
    {
        $this->checkField($field);
        $select = DB::table('statistics_customer_day');
        switch ($field) {
            case 'send_money' :
                $select = $select->selectRaw("SUM(amount) as money,dates");
                break;
            case 'order_num' :
                $select = $select->selectRaw("SUM(order_volume) as money,dates");
                break;
            case 'cost_money' :
                $select = $select->selectRaw("SUM(cost) as money,dates");
                break;
            case 'order_money' :
                $select = $select->selectRaw("SUM(order_money) as money,dates");
                break;
            case 'profit_money' :
                $select = $select->selectRaw("SUM(ROUND(amount-cost,2)) as money,dates");
                break;
            case 'profit_rate' :
                $select = $select->selectRaw("IF(SUM(amount) > 0,ROUND((SUM(ROUND(amount-cost,2))/SUM(amount))*100,2),0) as money,dates");
                break;
        }
        $list = $select->whereBetween('timestamps',[strtotime($start_time),strtotime($end_time)])->groupBy('timestamps')->get()->keyBy('dates')->toArray();
        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);
        $interval = ceil(($end_time - $start_time)/86400);
        $data = [];
        for ($i = 0; $i <= $interval; $i++) {
            $k = $start_time + $i * 86400;
            $date = date("Y-m-d",$k);
            if (isset($list[$date])) {
                $data[] = $list[$date];
            } else {
                $data[] = [
                    'money' => 0,
                    'dates' => $date
                ];
            }
        }
        return $data;
    }

    protected function checkField($field)
    {
        if (!in_array($field,['send_money','cost_money','order_money','profit_money','profit_rate'])) {
            return [];
        }
    }

    public function list(BaseRequest $request)
    {
        $start_time = $request->query('star_time') ?? date("Y-m-d");
        $end_time = $request->query('end_time') ?? date("Y-m-d");
        $field = $request->query('field') ?? 'send_money';
        $orderBy = $request->query('orderBy') ?? 'desc';
        $per_page = $request->query('per_page') ?? 20;
        $page = $request->query('page') ?? 1;

        $this->checkField($field);

        $list = DB::table('statistics_customer_day')->selectRaw("SUM(order_volume) as order_num,SUM(order_money) as order_money,SUM(amount) as send_money,SUM(cost) as cost_money,SUM(ROUND(amount-cost,2)) as profit_money,IF(SUM(amount) > 0,ROUND((SUM(ROUND(amount-cost,2))/SUM(amount))*100,2),0) as profit_rate,(SELECT company_name FROM ".config('database.connections.mysql.prefix')."company WHERE company_id=id) as company_name,company_id")
            ->whereBetween('timestamps',[strtotime($start_time),strtotime($end_time)])
            ->orderBy($field,$orderBy)->groupBy('company_id')->get();
        if ($list->isEmpty()) {
            return $this->success(['list'=>[],'total'=>0]);
        }
        $total = $list->count();
        $all = $list->chunk($per_page);
        if (isset($all[$page-1])) {
            $list = $all[$page-1];
            $list = array_values($list->toarray());
        } else {
            $list = [];
        }
        return $this->success(['list'=>$list,'total'=>$total]);
    }
}
